package com.slx.sthq.controller;


import com.slx.sthq.config.SeaweedFSConfig;
import com.slx.sthq.domain.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
@Api(value = "使用seaweedFs上传文件", tags = "使用seaweedFs上传文件")
@RequestMapping("/seaweed")
public class FileUploadController {

    @Autowired
    private SeaweedFSConfig seaweedFSConfig;

    @PostMapping("/upload")
    @ApiOperation("上传")
    public R uploadFile(@RequestParam("path") String path, @RequestPart(value = "file") MultipartFile file) {
        try {
            String uploadpath = seaweedFSConfig.uploadFile(file, path);
            return R.ok(uploadpath);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(204, "上传失败");
        }
    }


    @GetMapping("/download")
    @ApiOperation("下载")
    public void download(HttpServletResponse response, @RequestParam("filePath") String filePath) throws IOException {
        byte[] buf = seaweedFSConfig.downloadFile(filePath);
        String fileName = seaweedFSConfig.getLastSegment(filePath);
        // 设置响应头
        seaweedFSConfig.setResponseHeaders(response, fileName);
        // 写入响应内容
        seaweedFSConfig.writeToResponse(response, buf);
    }


    /**
     * 删除文件
     *
     * @param filePath 文件的完整路径
     * @return 删除结果
     */
    @DeleteMapping("/delete")
    @ApiOperation("删除")
    public R deleteFile(@RequestParam String filePath) {
        try {
            seaweedFSConfig.deleteFile(filePath);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(201, e.getMessage());
        }
    }

}
